using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Unicode;
using Mathmall.Administration.Data;
using Mathmall.Administration.Helper;
using Mathmall.Administration.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;

namespace Mathmall.Administration.Authorization;

public class OperationHandler : AuthorizationHandler<OperationRequirement>
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly JwtHelper _jwtHelper;

    public OperationHandler(IHttpContextAccessor httpContextAccessor, JwtHelper jwtHelper)
    {
        _httpContextAccessor = httpContextAccessor;
        _jwtHelper = jwtHelper;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        OperationRequirement requirement)
    {
        Console.WriteLine(requirement.Operation);
        // 从请求头中拿到jwt
        string jwtString = JsonSerializer.Serialize(_httpContextAccessor.HttpContext!.Request.Headers["token"]);
        // 解析jwt,获取用户权限
        IQueryable<Menu?> menus = _jwtHelper.JwtParser(jwtString);
        foreach (var menu in menus)
        {
            if (requirement.Operation.Equals(menu.AuthorityValue))
            {
                context.Succeed(requirement);
            }
        }

        return Task.CompletedTask;
    }
}